package wschat.tcp;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

/**
 * Created by alex on 15-1-26.
 */
@Component
public class TcpClient {

    public static final Logger LOG = LoggerFactory.getLogger(TcpClient.class);
    
    @Autowired
    @Qualifier("clientBootstrap")
    private Bootstrap bootstrap;
    
    @Autowired
    @Qualifier("remoteAddress")
    private InetSocketAddress remoteAddress;
    
    private ChannelFuture channelFuture;

    @PostConstruct
    public void connect() throws Exception {
        LOG.info("client connect server");
        channelFuture = bootstrap.connect(remoteAddress).sync();
        //channelFuture.channel().closeFuture().sync();
    }
    
    @PreDestroy
    public void destroy()throws Exception{
        channelFuture.channel().closeFuture().sync();
    }
}
